import React, { useEffect } from 'react';
import { Button, Checkbox, Form, Input, message } from 'antd';
import { useNavigate } from 'react-router-dom';
import axios from 'axios';
import bgImg from '../../assets/bg.jpg'


const LoginForm: React.FC = () => {
  const [messageApi, contextHolder] = message.useMessage();
  const navigate = useNavigate()
  // 提交并登录
  const onFinish = (values: any) => {
    axios.post('/login', values).then(res => {
      if(res.data.code === 0) {
        localStorage.setItem('userInfo', JSON.stringify(res.data.data.userInfo))
        messageApi.open({
          type: 'loading',
          content: '登录成功，正在跳转',
          duration: 1.5
        }).then(() => {
          navigate('/userlist')
        });
      } else {
        messageApi.open({
          type: 'error',
          content: res.data.data.msg,
        });
      }
    })
    // 根据勾选记住，设置或删除本地缓存用户名
    if(values.remember) {
      localStorage.setItem('username', values.username)
      localStorage.setItem('password', values.password)
    } else {
      localStorage.removeItem('username')
      localStorage.removeItem('password')
    }
  };


  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };
  const [form] = Form.useForm()
  const checked = localStorage.getItem('username') ? true : false;
  if(checked) {
    // 
    useEffect(() => {
      console.log(123)
      form.setFieldsValue({
        username: localStorage.getItem('username'),
        password: localStorage.getItem('password')
      })
    }, [form]);
  }
  return (
    <div style={{ display: 'flex', justifyItems: 'center', alignItems: 'center', height: '100vh',background: `url(${bgImg})`, backgroundSize: 'cover' }}>
      <Form
        name="basic"
        form={form}
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 16 }}
        style={{ flex: '0 0 600px', background: 'rgba(0,0,0,.1)', maxWidth: 600, margin: '0 auto', padding: '50px 30px 30px', borderRadius: 8 }}
        initialValues={{ remember: checked }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
      >
        <Form.Item
          label="用户名"
          name="username"
          rules={[{ required: true, message: '请输入用户名' }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="密码"
          name="password"
          rules={[{ required: true, message: '请输入密码' }]}
        >
          <Input.Password />
        </Form.Item>

        <Form.Item name="remember" valuePropName="checked" wrapperCol={{ offset: 5, span: 16 }}>
          <Checkbox>记住我</Checkbox>
        </Form.Item>

        <Form.Item wrapperCol={{ offset: 5, span: 16 }}>
          <Button type="primary" htmlType="submit">
            登录
          </Button>
        </Form.Item>
      </Form>
      { contextHolder }
    </div>
  )
};

export default LoginForm;